/**
 * @Author: easten
 * @Created: 2024-04-15 23:48:14
 * @Description:
 *
 */
import { ApiPermission } from "_common/api/sys";
import { DrawerProps } from "_common/DataType";
import { SysPermission } from "_common/entity";
import React, { useState, useEffect, useRef } from "react";
import {
  Button,
  Drawer,
  Form,
  FormInstanceFunctions,
  Input,
  InputNumber,
} from "tdesign-react";
import FormItem from "tdesign-react/es/form/FormItem";
type PermissionDrawerProps = DrawerProps & {};
const PermissionDrawer: React.FC<PermissionDrawerProps> = (
  props: PermissionDrawerProps
) => {
  const { open, axios, edit, onSuccess, value } = props;
  const formRef = useRef<FormInstanceFunctions>();

  // 是否展示父级权限
  const [showParent, setShowParent] = useState<boolean>(false);
  const apiPermission = new ApiPermission(axios!);

  useEffect(() => {
    return () => {
      formRef.current?.reset();
      setShowParent(false);
    };
  }, []);

  useEffect(() => {
    if (!open) {
      setShowParent(false);
      formRef.current?.reset();
    }
  }, [open]);

  useEffect(() => {
    if (value && edit) {
      formRef.current?.setFieldsValue(value);
      if (value.parentId) {
        setShowParent(true);
        const _time = setTimeout(() => {
          formRef.current?.setFieldsValue({ parent: value.parent.name });
          clearTimeout(_time);
        }, 100);
      }
    }

    if (!edit && value) {
      setShowParent(true);
      const _time = setTimeout(() => {
        formRef.current?.setFieldsValue({ parent: value.name });
        clearTimeout(_time);
      }, 100);
    }
  }, [edit, value, open]);

  const handleClose = () => {
    onSuccess?.(false);
    formRef.current?.reset();
  };

  // 新增用户
  const createPermission = async (data: SysPermission) => {
    if (value) {
      data.parentId = value.id;
    }
    const response = await apiPermission.create(data);
    if (response && response.code === 200) {
      handleClose();
    }
  };
  // 更新用户
  const updatePermission = async (data: SysPermission) => {
    const response = await apiPermission.update({
      ...data,
      id: value?.id,
      parentId: value?.parentId,
    });
    if (response && response.code === 200) {
      handleClose();
    }
  };

  return (
    <Drawer
      header={`${edit ? "编辑" : "添加"}权限`}
      footer={false}
      visible={open}
      sizeDraggable
      size="medium"
      onClose={handleClose}
    >
      <Form
        ref={formRef}
        labelWidth={100}
        onSubmit={(data) => {
          edit
            ? updatePermission(data.fields as SysPermission)
            : createPermission(data.fields as SysPermission);
        }}
      >
        {showParent && (
          <FormItem label="父级" rules={[{ required: true }]} name="parent">
            <Input readonly />
          </FormItem>
        )}
        <FormItem label="权限名称" rules={[{ required: true }]} name="name">
          <Input />
        </FormItem>
        <FormItem label="权限编码" rules={[{ required: true }]} name="code">
          <Input placeholder="权限编码唯一，不要随意改动" />
        </FormItem>
        <FormItem label="排序号" name="sortCode">
          <InputNumber defaultValue={0} />
        </FormItem>
        <FormItem className="float-right">
          <Button type="submit" theme="primary">
            提交
          </Button>
          <Button type="reset" theme="success" style={{ marginLeft: 12 }}>
            重置
          </Button>
        </FormItem>
      </Form>
    </Drawer>
  );
};
export default PermissionDrawer;
